//
//  WKUserAccountViewModel.swift
//  WKWeibo
//
//  Created by 恋guang年 on 16/3/26.
//  Copyright © 2016年 恋guang年. All rights reserved.
//发现控制需要 字典转模型、 保存模型到沙盒,后续可能还需要 从沙盒加载用户信息 等对 CZUserAccount 的操作, 创建 CZUserAccountViewModel 类来专门处理 CZUserAccount 相关的操作 减小控制器压力

import UIKit

class WKUserAccountViewModel: NSObject {
    static let sharedInstance = WKUserAccountViewModel()
    //私有化构造方法
    override init(){
        super.init()
        /// 从沙盒加载账号
        userAccount = loadUserAccount()
    }
    //用户信息属性
    var userAccount : WKUserAccount?
    ///  获取收取 得到AccessTokenuserAccount
    var isUserLogin:Bool{
        get {
            return userAccount != nil
        }
    }
    
    
    /// 根据请求授权成功得到的code 获得授权 得到用户AccessToken
    func loadAccessToken(code : String, completion: (error: NSError?) -> () ){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        /*
        根据新浪API文档要求拼接POST请求参数
        */
        
        let parameters = ["client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri]
        //发送请求
        WKNetWorkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil{
                print("请求AccessToken出错error=\(error)")
                completion(error: error)
                return
            }
            //获得WKUserAccount模型
            self.userAccount = WKUserAccount(dict: result!)
            //用户信息保存到沙盒
            self.saveUserAccount()
            completion(error: nil)
        }
        
    }
    ///加载用户头像和昵称
    func loadUserInfo(complection: (error:NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters:[String : AnyObject] = ["access_token":(userAccount?.access_token)!,"uid":(userAccount?.uid)!]
        WKNetWorkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil{
                print("加载用户头像或昵称出错:\(error)")
                return
            }
            //给用户 screen_name avatar_large 赋值
            self.userAccount?.screen_name = result!["screen_name"] as? String
            self.userAccount?.avatar_large = result!["avatar_large"] as? String
            //保存用户信息到沙盒
            self.saveUserAccount()
        }
    }
    /// 保存账号信息的路径
    private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/account.plist")
    ///  账号信息保存到沙盒
    private func saveUserAccount(){
        if userAccount != nil{
            // 有账号才需要保存
            print("accountPath: \(accountPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath!)
        }
    }
    
    /// 从沙盒加载数据
    private func loadUserAccount() -> WKUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? WKUserAccount
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("userAccount: \(userAccount)")
            return userAccount
        }
        
        return nil
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
